//
//  HomepageViewController.m
//  Tour
//
//  Created by 张张烨 on 16/3/7.
//  Copyright © 2016年 张中烨. All rights reserved.
//

#import "HomepageViewController.h"
#import "AppDelegate.h"

@interface HomepageViewController () <UITableViewDataSource, UITableViewDelegate, CarouselPictureDelegate, pushWebDelegate>
@property (nonatomic, strong) NSMutableArray *tableviewDataArr; /**< tableview数据数组 */
@property (nonatomic, strong) NSMutableArray *photosArr; /**< 轮播图数组 */
@property (nonatomic, strong) NSMutableArray *subjectArr; /**< 专题数组 */
@property (nonatomic, strong) BaseView *headerView; /**< tableview头部视图 */
@property (nonatomic, strong) BaseTableView *tableview; /**< tableview */
@property (nonatomic, assign) NSInteger page; /**< 刷新时的变化值 */
@property (nonatomic, strong) CarouselPicture *carouse; /**< 轮播图 */
@property (nonatomic, strong) NSMutableArray *subjectWebStrArr; /**< 专题详情网址 */
@property (nonatomic, strong) UIButton *signButton;/**< 登录按钮 */
@property (nonatomic, strong) UIView *backView;
@end

@implementation HomepageViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
#if 0
    NSString *perPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"d.aaaaaaaa"];
    NSString *str = [NSKeyedUnarchiver unarchiveObjectWithFile:perPath];
    /**<  夜间没事 */
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    
    
    self.backView  = [[UIView alloc] initWithFrame:FRAME];
    
    UIImageView *img= [[UIImageView alloc]initWithFrame:FRAME];
    
    img.image =[UIImage imageNamed:str];

    self.backView.tag =1000;
    [self.backView addSubview:img];
    self.backView.alpha = 0.3;
    self.backView.userInteractionEnabled = NO;
    [delegate.window addSubview:_backView];
    self.backView.hidden = NO;
    
#endif
    
    //获取上进入程序的日期
//    NSDate *date = [[NSUserDefaults standardUserDefaults] objectForKey:@"date"];
//    //判断是不是同一天,如果是就不改变按钮的状态,如果不是就改变按钮状态并将新的时间存储
//    if (date) {
//        //获取当前的时间
//        NSCalendar *cal = [NSCalendar currentCalendar];
//        NSUInteger unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
//        NSDateComponents * component= [cal components:unitFlags fromDate:[NSDate date]];
//        NSDate *today = [cal dateFromComponents:component];
//        if ([today isEqualToDate:date]) {
//            self.signButton.selected = YES;
//            //开启交互
//            self.signButton.userInteractionEnabled = NO;
//            
//        }else {
//            self.signButton.selected = NO;
//            self.signButton.userInteractionEnabled = YES;
//        }
//    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //标题
    self.navigationItem.title = @"推荐";
    
    //初始化刷新变化值
    self.page = 1;
    
    //初始化tableview数组
    self.tableviewDataArr = [NSMutableArray array];
    
    //创建视图
    [self createSubviews];
    //处理数据
    [self carouseDataHandler];
    [self hotTravelNotesDatahandler];
    [self subjectDataHandler];
    //刷新加载
    [self creatRefresh];
    //判断网络
    [self networkJudgeWith:self];
}


///创建视图
- (void)createSubviews
{
        //右上角的搜索键
    UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"搜索"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(searchAddress)];
    self.navigationItem.rightBarButtonItem = searchButton;
    //左上角日历
    UIBarButtonItem *calendarButton = [[UIBarButtonItem alloc]
                                       initWithImage:[[UIImage imageNamed:@"000"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(calendarAction)];
    //签到按钮
//    UIBarButtonItem *signButton = [[UIBarButtonItem alloc] initWithTitle:@"签到" style:UIBarButtonItemStylePlain target:self action:@selector(signAction)];
    
    self.navigationItem.leftBarButtonItem = calendarButton ;
    
    
    //创建tableview
    self.tableview = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 79)];
    [self.view addSubview:_tableview];
    _tableview.dataSource = self;
    _tableview.delegate = self;
    // 隐藏滚动条
    _tableview.showsVerticalScrollIndicator = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    _tableview.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //注册重用池
    [_tableview registerClass:[HomepageTravelCell class] forCellReuseIdentifier:@"cell"];
    
    //初始化头部视图
    self.headerView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 2 + SCREEN_HEIGHT / 4)];
    _tableview.tableHeaderView = _headerView;
//    [_tableview NightWithType:UIViewColorTypeNormal];

}

/// 轮播图数据处理
- (void)carouseDataHandler
{
   [MBProgressHUDManager showHUDtoView:self.view string:@"正在加载中..."];
    
    [AFNModel GETWithHandler:@"http://api.breadtrip.com/v2/index/?lat=38.88251053030555&lng=121.5398154525028&sign=66b602bbfb4a0eec4a632cadece8b7b8" completion:^(id result) {
        
        //   数据处理
        for (NSDictionary *dic in result[@"data"][@"elements"]) {
            if ([@"1" isEqualToString:[dic[@"type"] stringValue]]) {
                
                NSMutableArray *arr = dic[@"data"];
                // dic[@"data"] 中只有一个数组
                NSMutableArray *arr1 = arr[0];
                
                // 获取轮播图图片数组
                self.photosArr = [NSMutableArray array];
                for (NSDictionary *dic in arr1) {
                    // 逐个加入 轮播图数组中
                    [self.photosArr addObject: dic[@"image_url"]];
                }
                //                NSLog(@"轮播图数组: %@",_photos);
                
                // 获取webView网址数组
                NSMutableArray *urlArr = [NSMutableArray array];
                for (NSDictionary *dic in arr1) {
                    
                    // 逐个加入 webView 网址数组中(需要初始化)
                    [urlArr addObject:dic[@"html_url"]];
                }

                //创建轮播图
                self.carouse = [[CarouselPicture alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 4) timeInterval:2 imageUrlArr:_photosArr urlArr:urlArr];
                self.carouse.delegate = self;
                [self.headerView addSubview:_carouse];
                
                //签到按钮
//                self.signButton = [UIButton buttonWithType:UIButtonTypeCustom];
//                _signButton.frame = CGRectMake(0, 0, 64, 64);
//                _signButton.center = CGPointMake(SCREEN_WIDTH / 5 * 4, _carouse.center.y);
////                [_signButton setTitle:@"立即签到" forState:UIControlStateNormal];
//                [_signButton setImage:[UIImage imageNamed:@"2-2"] forState:UIControlStateNormal];
//                [_signButton setImage:[UIImage imageNamed:@"yq"] forState:UIControlStateSelected];
//                
//                [_signButton setTitle:@"今日已签到" forState:UIControlStateSelected];
//                _signButton.titleLabel.font = [UIFont systemFontOfSize:14];
//                [_signButton setBackgroundColor:[UIColor cyanColor]];
//                [_signButton addTarget:self action:@selector(signAction) forControlEvents:UIControlEventTouchUpInside];
//                [self.carouse addSubview:_signButton];
                
                //获取上进入程序的日期
                NSDate *date = [[NSUserDefaults standardUserDefaults] objectForKey:@"date"];
                //判断是不是同一天,如果是就不改变按钮的状态,如果不是就改变按钮状态并将新的时间存储
                if (date) {
                    //获取当前的时间
                    NSCalendar *cal = [NSCalendar currentCalendar];
                    NSUInteger unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
                    NSDateComponents * component= [cal components:unitFlags fromDate:[NSDate date]];
                    NSDate *today = [cal dateFromComponents:component];
                    if ([today isEqualToDate:date]) {
                        self.signButton.selected = YES;
                        //开启交互
                        self.signButton.userInteractionEnabled = NO;
                        
                    }else {
                        self.signButton.selected = NO;
                        self.signButton.userInteractionEnabled = YES;
                    }
                }

                
            }
            
        }
    }];
}

///精彩专题数据处理
- (void)subjectDataHandler
{
    NSDictionary *value = [HomepageViewController getCache:1 andId:1];
    if (value) {
        self.subjectArr = value[@"data"][@"subject"];
        [self createSubjectView];
        [MBProgressHUDManager removeHUD];
    }else {
    
    [AFNModel GETWithHandler:@"http://open.qyer.com/qyer/recommands/entry?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=38.88243146147855&lon=121.5398488177902&page=1&track_app_channel=App%2520Store&track_app_version=6.8.3&track_device_info=iPhone7%2C2&track_deviceid=0C79B4F1-2C09-4E9A-805E-05836431AB22&track_os=ios%25209.2&v=1" completion:^(id result) {
        
        //将解析出的数据存储起来
        [HomepageViewController saveCache:1 andID:1 andDic:result];
        
     self.subjectArr = result[@"data"][@"subject"];
    
        [self createSubjectView];
        
     }];
    }
}

//中间视图创建
- (void)createSubjectView
{
    self.subjectWebStrArr = [NSMutableArray array];
    [_subjectWebStrArr addObject: _subjectArr[0][@"url"]];
    [_subjectWebStrArr addObject: _subjectArr[1][@"url"]];
    [_subjectWebStrArr addObject: _subjectArr[2][@"url"]];
    
    //创建中间位置视图
    SubjectView *subjectView = [[SubjectView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT / 4, SCREEN_WIDTH, SCREEN_HEIGHT / 2) urlStrArr:_subjectWebStrArr];
    subjectView.delegate = self;
    
    [subjectView NightWithType:UIViewColorTypeNormal];
    [self.headerView addSubview:subjectView];
    //赋值
    [subjectView.bigImageView sd_setImageWithURL:[NSURL URLWithString:_subjectArr[0][@"photo"]]];
    [subjectView.leftImageView sd_setImageWithURL:[NSURL URLWithString:_subjectArr[1][@"photo"]]];
    [subjectView.rightImageView sd_setImageWithURL:[NSURL URLWithString:_subjectArr[2][@"photo"]]];
    //看更多热门点击事件
    [subjectView.moreSubjectButton addTarget:self action:@selector(moreSubjectAction) forControlEvents:UIControlEventTouchUpInside];
}

/// 热门游记数据处理
- (void)hotTravelNotesDatahandler
{
    NSDictionary *value = [HomepageViewController getCache:1 andId:2];
    if (value) {
        // 判断 如果 page值为1  为下拉刷新
        if (_page == 1) {
            // 清空里面所有数据 重新获取 添加
            [self.tableviewDataArr removeAllObjects];
            
            NSArray *dataArr = value[@"data"];
            //        NSLog(@"%@",dataArr);
            for (NSDictionary *dic in dataArr) {
                //  使用便利构造器
                HomeModal *modal = [HomeModal modelWithDic:dic];
                //            NSLog(@"%@", modal);
                //viewDidLoad 中初始化数组 (否则无法添加)
                // 逐个将对象添加到数组中
                [self.tableviewDataArr addObject:modal];
            }
            //        NSLog(@"tableviewData:%@", _tableviewDataArr);
            //数据重载
            [_tableview reloadData];
            // 结束刷新
            [self.tableview.mj_header endRefreshing];
            [self.tableview.mj_footer endRefreshing];
        }else
        {
            [self hotHandler];
        }
        
    }else {
        [self hotHandler];
    }
}

- (void)hotHandler
{
    /**< 网址拼接 */
    NSString *url = [NSString stringWithFormat:@"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&oauth_token=89dd34fbffaaa72503b4baa7a9d02812&page=%ld",(long)_page];
    NSString *str = @"&track_app_channel=App%2520Store&track_app_version=6.8.3&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=CDA3EEEB-61BF-473E-AFFF-32B6332C9BBF&track_os=ios%25207.1.2&track_user_id=7328550&type=index&v=1";
    [AFNModel GETWithHandler:[NSString stringWithFormat:@"%@%@",url,str] completion:^(id result) {
        
        [HomepageViewController saveCache:1 andID:2 andDic:result];
        // 判断 如果 page值为1  为下拉刷新
        if (_page == 1) {
            // 清空里面所有数据 重新获取 添加
            [self.tableviewDataArr removeAllObjects];
        }
        NSArray *dataArr = result[@"data"];
        //        NSLog(@"%@",dataArr);
        for (NSDictionary *dic in dataArr) {
            //  使用便利构造器
            HomeModal *modal = [HomeModal modelWithDic:dic];
            //            NSLog(@"%@", modal);
            //viewDidLoad 中初始化数组 (否则无法添加)
            // 逐个将对象添加到数组中
            [self.tableviewDataArr addObject:modal];
        }
        //        NSLog(@"tableviewData:%@", _tableviewDataArr);
        //数据重载
        [_tableview reloadData];
        // 结束刷新
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        
        [MBProgressHUDManager removeHUD];
    }];
    
}
///tableview方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableviewDataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomepageTravelCell *cell  = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    HomeModal *modal = _tableviewDataArr[indexPath.row];
    // 标题
    cell.title.text = modal.title;
    
    [cell.title NightWithType:UIViewColorTypeNormal];
    
    // 图片
    [cell.photo sd_setImageWithURL:[NSURL URLWithString:modal.photo]placeholderImage:[UIImage imageNamed:@"zhanweitu.jpg"]];
    
    // 用户名
    cell.username.text = modal.username;

    // 评论
    cell.replys.text = modal.replys;
//    [cell.replys NightWithType:UIViewColorTypeNormal];
    // 查看
    cell.views.text = [modal.views stringValue];
//    [cell.views NightWithType:UIViewColorTypeNormal];
    
    [cell NightWithType:UIViewColorTypeNormal];
    return cell;
}
//点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消tableView选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 跳转隐藏 tabbar
    self.hidesBottomBarWhenPushed=YES;
    // 跳转webView
    HomeCarouseWebVC *webview = [[HomeCarouseWebVC alloc]init];
    HomeModal *model = _tableviewDataArr[indexPath.row];
    webview.urlstr = model.view_url;
    webview.title = model.title;
    [self.navigationController pushViewController:webview animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

#pragma mark - 轮播图封装 实现点击协议方法
- (void)pushWithUrl:(NSString *)url
{
    // 跳转webView
    HomeCarouseWebVC *webview = [[HomeCarouseWebVC alloc]init];
    // 跳转隐藏 tabbar
    self.hidesBottomBarWhenPushed=YES;
    
    // url =  self.urlArr[self.page]; // 网址数组中第几个图片
    webview.urlstr = url;
    [self.navigationController pushViewController:webview animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;

}
#pragma mark - 专题视图点击协议方法实现
- (void)pushBigWebWithUrl:(NSString *)urlStr
{
    // 跳转webView
    HomeCarouseWebVC *webview = [[HomeCarouseWebVC alloc]init];
    // 跳转隐藏 tabbar
    self.hidesBottomBarWhenPushed=YES;
    
    // url =  self.urlArr[self.page]; // 网址数组中第几个图片
    webview.urlstr = urlStr;
    [self.navigationController pushViewController:webview animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
}
#pragma mark - 上拉刷新,下拉加载
- (void)creatRefresh
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        /**< 下拉刷新数据处理, */
        [self refreshData];
    }];
    self.tableview.mj_header = header;
    [header setTitle:@"玩命加载中..." forState:MJRefreshStatePulling];
    
    /**< 开始刷新 */
    [header beginRefreshing];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        /**< page自加 */
        _page++;
        // tableview 数据处理
        [self hotTravelNotesDatahandler];
    }];
}
/// 下拉刷新 获取最初的数据
- (void)refreshData{
    // 初始数据page值为1
    _page = 1;
    // 进行数据处理
    [self hotTravelNotesDatahandler];
}

///更多热门点击方法
- (void)moreSubjectAction
{
    // 跳转隐藏tabbar
    self.hidesBottomBarWhenPushed=YES;
    HomepageMoreSubjectVC *getMoreVC = [[HomepageMoreSubjectVC alloc]init];
    [self.navigationController pushViewController:getMoreVC animated:YES];
    // 跳转隐藏tabbar
    self.hidesBottomBarWhenPushed=NO;
}
///搜索栏方法
- (void)searchAddress
{
    HomeSearchVC *searchVC = [[HomeSearchVC alloc] init];
    BaseNavigationController *navi = [[BaseNavigationController alloc] initWithRootViewController:searchVC];
    [self presentViewController:navi animated:YES completion:^{
        
    }];
}

///日历方法
- (void)calendarAction
{
    HomeCalendarVC *calendar = [[HomeCalendarVC alloc] init];
    [self.navigationController pushViewController:calendar animated:YES];
}

//签到按钮方法
- (void)signAction
{
//    _signButton.selected = !_signButton.selected;
//    //关闭用户交互,禁止点击
//    _signButton.userInteractionEnabled = NO;
//    
//    //获取当前的时间
//    NSCalendar *cal = [NSCalendar currentCalendar];
//    NSUInteger unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
//    NSDateComponents * component= [cal components:unitFlags fromDate:[NSDate date]];
//    NSDate *today = [cal dateFromComponents:component];
//    //将日期保存在单例里面
//    [[NSUserDefaults standardUserDefaults] setObject:today forKey:@"date"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
